<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport"="width=device-width, initial-scale=1.0">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <title>管理员面板</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- 引入jQuery库，方便进行AJAX操作 -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> <!-- 引入完整的Bootstrap JavaScript插件 -->
  <style>
        /* 自定义样式，用于美化比赛管理表格等展示效果 */
        table#contestTable {
            width: 100%;
            border-collapse: collapse;
        }

        table#contestTable th,
        table#contestTable td {
            border: 1px solid #ccc;
            padding: 8px;
            text-align: left;
        }

        table#contestTable th {
            background-color: #f2f2f2;
        }

        button.btn-sm {
            margin-right: 5px;
        }
		
		.dropdown-menu.show-dropdown {
			display: block;
		}

		.dropdown-menu.hide-dropdown {
			display: none;
		}

    </style>
</head>

<body>
  <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <div class="container-fluid">
      <a class="navbar-brand" href="#">管理员面板</a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
              aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav">
          <li class="nav-item">
            <a class="nav-link" data-bs-toggle="pill" href="#createUserSection">首页</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" data-bs-toggle="pill" href="#batchCreateUserSection">批量创建用户</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" data-bs-toggle="pill" href="#userManagementSection">用户管理</a>
          </li>
		  <li class="nav-item">
            <a class="nav-link" data-bs-toggle="pill" href="#contestSection">比赛管理</a>
          </li>
        </ul>
      </div>
      <div class="navbar-nav ms-auto"> <!-- 使用ms-auto将此部分靠右对齐 -->
        <div class="dropdown">
			<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false">
				欢迎您
			</button>
			<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton">
				<li><a class="dropdown-item" href="#" id="logoutBtn">退出登录</a></li>
			</ul>
		</div>
		
		
		
		<script>
			$(document).on('click', '#dropdownMenuButton', function (event) {
				event.preventDefault(); // 阻止按钮默认行为，比如避免链接跳转等情况（虽然这里按钮本身没有链接跳转，但以防万一）
				event.stopPropagation(); // 阻止事件冒泡，防止其他外层元素绑定的点击事件干扰下拉菜单显示逻辑
				var dropdownMenu = $(this).next('.dropdown-menu');
				if (dropdownMenu.hasClass('show-dropdown')) {
					dropdownMenu.removeClass('show-dropdown').addClass('hide-dropdown');
				} else {
					dropdownMenu.removeClass('hide-dropdown').addClass('show-dropdown');
				}
				console.log("点击了，下拉菜单");
			});
			$(document).ready(function () {
				// 点击退出登录按钮的事件处理
				$(document).on('click', '#logoutBtn', function (e) {
					e.preventDefault();
					$.ajax({
						type: "POST",
						url: "/logout",
						dataType: "json",
						success: function (response) {
							if (response.success) {
								// 成功退出登录后直接跳转到登录页面
								window.location.href = "/";
							} else {
								alert(response.message);
							}
						},
						error: function (xhr, status, error) {
							// 记录错误日志以便调试
							console.error('退出登录请求出现错误:', xhr, status, error);
							// 给用户提供更友好的错误提示
							alert("退出登录时发生错误，请检查网络连接或稍后重试。");
						}
					});
				});
			});
		</script>
      </div>
    </div>
  </nav>
  <div class="container mt-5">
    <div class="tab-content">
      <!-- 单独创建用户功能区域 -->
        <div class="tab-pane fade show active" id="createUserSection">
           <h2>首页</h2>
            <!-- 单独创建用户表单 -->
            <form id="createUserForm" method="POST" action="/create_user">
                <div class="mb-3">
                    <label for="new_username" class="form-label">用户名：</label>
                    <input type="text" id="new_username" name="new_username" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label for="new_password" class="form-label">密码：</label>
                        <input type="password" id="new_password" name="new_password" class="form-control" required>
                    </div>
                    <input type="submit" value="创建用户" class="btn btn-primary">
                </form>
				
				
                <!-- 创建比赛功能区域 -->
				<h3>创建比赛</h3>
				<form id="createCompetitionForm">
					<div class="mb-3">
						<label for="competition_name" class="form-label">比赛名称：</label>
						<input type="text" id="competition_name" name="competition_name" class="form-control" required>
					</div>
					<div class="mb-3">
						<label for="competition_deadline" class="form-label">比赛截止时间：</label>
						<input type="datetime-local" id="competition_deadline" name="competition_deadline"
							   class="form-control" required>
					</div>
					<script>
						$(document).ready(function () {
							var today = new Date();
							var year = today.getFullYear();
							var month = String(today.getMonth() + 1).padStart(2, '0');
							var day = String(today.getDate()).padStart(2, '0');
							var hours = String(today.getHours()).padStart(2, '0');
							var minutes = String(today.getMinutes()).padStart(2, '0');
							var seconds = String(today.getSeconds()).padStart(2, '0');
							var currentDateTime = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
							$('#competition_deadline').val(currentDateTime);
						});
					</script>
					<div class="mb-3">
						<label for="question_num" class="form-label">题目数量：</label>
						<select id="question_num" name="question_num" class="form-select" required>
							<option value="0">0</option>
							<option value="1">1</option>
							<option value="2">2</option>
							<option value="3">3</option>
							<option value="4">4</option>
							<option value="5">5</option>
							<option value="6">6</option>
							<option value="7">7</option>
							<option value="8">8</option>
							<option value="9">9</option>
							<option value="10">10</option>
						</select>
					</div>
					<div id="questionInputs"></div>
					<input type="button" value="创建比赛" class="btn btn-success" id="createCompetitionBtn">
				</form>
				<script>
					// 当题目数量选择框的值改变时，动态生成或删除题目输入框
					$('#question_num').on('change', function () {
						var questionNum = $(this).val();
						var questionInputsDiv = $('#questionInputs');
						questionInputsDiv.empty();
						for (var i = 1; i <= questionNum; i++) {
							var questionInput = '<div class="mb-3"><label for="question_name_' + i + '" class="form-label">题目' + i + '名称：</label><input type="text" id="question_name_' + i + '" name="question_name_' + i + '" class="form-control" required></div>';
							questionInputsDiv.append(questionInput);
						}
					});

					// 创建比赛按钮点击事件处理
					$('#createCompetitionBtn').on('click', function () {
						var competitionName = $('#competition_name').val();
						var competitionDeadline = $('#competition_deadline').val();
						var questionNum = $('#question_num').val();
						var questions = [];
						for (var i = 1; i <= questionNum; i++) {
							var questionName = $('#question_name_' + i).val();
							questions.push(questionName);
						}
						var formData = {
							"competition_name": competitionName,
							"competition_deadline": competitionDeadline,
							"questions": questions
						};
						$.ajax({
							type: "POST",
							url: "/create_competition",
							contentType: "application/json",
							data: JSON.stringify(formData),
							dataType: "json",
							success: function (response) {
								if (response.success) {
									console.log("比赛创建成功了")
									alert(response.message);
									// 可根据需求添加刷新比赛列表等操作
									
									loadContestList();
								} else {
									alert(response.message);
								}
							},
							error: function (xhr, status, error) {
								console.log('创建比赛请求出现错误:', xhr, status, error);
								alert("创建比赛出现错误，请稍后再试");
							}
						});
					});
				</script>
            </div>
	  
	  
      <!-- 批量创建用户功能区域 -->
      <div class="tab-pane fade" id="batchCreateUserSection">
        <h2>批量创建用户</h2>
        <form id="batchCreateUserForm" method="POST" action="/batch_create_users">
          <div class="mb-3">
            <label for="prefix" class="form-label">账号前缀：</label>
            <input type="text" id="prefix" name="prefix" class="form-control" required>
          </div>
          <div class="mb-3">
            <label for="start_num" class="form-label">起始序号：</label>
            <input type="number" id="start_num" name="start_num" class="form-control" required min="1">
          </div>
          <div class="mb-3">
            <label for="end_num" class="form-label">结束序号：</label>
            <input type="number" id="end_num" name="end_num" class="form-control" required min="1">
          </div>
          <input type="submit" value="批量创建用户" class="btn btn-primary">
        </form>
      </div>
	  
      <!-- 用户管理功能区域 -->
      <div class="tab-pane fade" id="userManagementSection">
        <h2>用户管理</h2>
        <form id="batchActionsForm"> <!-- 新增用于批量操作的表单 -->
          <input type="hidden" id="action" name="action" value=""> <!-- 用于记录批量操作类型，如'reset_password'或'delete' -->
          <table class="table table-striped">
            <thead>
              <tr>
                <th><input type="checkbox" id="selectAllCheckbox">全选</th> <!-- 新增全选复选框 -->
                <th>ID</th>
                <th>用户名</th>
                <th>是否管理员</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody id="userList">
              <!-- 这里将通过JavaScript动态填充用户数据 -->
            </tbody>
          </table>
          <button type="button" class="btn btn-primary" id="batchResetPasswordBtn">批量重置密码</button> <!-- 新增批量重置密码按钮 -->
          <button type="button" class="btn btn-danger" id="batchDeleteBtn">批量删除</button> <!-- 新增批量删除按钮 -->
        </form>
      </div><!-- 用户管理功能区域 -->
	  
    </div>
  </div>
  
  <div class="modal fade" id="resetPasswordModal" tabindex="-1" aria-labelledby="resetPasswordModalLabel"
       aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="resetPasswordModalLabel">重置用户密码</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <input type="hidden" id="resetUserId" value="">
          <p>确定要将此用户密码重置为 <strong>12345</strong> 吗？</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary" id="confirmResetPassword">确认重置</button>
        </div>
      </div>
    </div>
  </div>
  
  

		<!-- 比赛管理功能区域 -->
		<div class="tab-pane fade" id="contestSection">
			<h2>比赛管理</h2>
			<div class="current-contest-info">
				<h3>当前正在进行的比赛ID：</h3>
				<h3><span id="currentContestId" style="bold"></span></h3>
			</div>
			<form id="batchContestActionsForm">
				<!-- 可添加筛选、搜索等表单元素，比如按比赛名称搜索等 -->
				<button type="button" class="btn btn-danger" id="batchDeleteContestBtn">批量删除比赛</button>
			</form>
			<table id="contestTable">
				<thead>
					<tr>
						<th><input type="checkbox" id="selectAllContestCheckbox">全选</th>
						<th>比赛ID</th>
						<th>比赛名称</th>
						<th>比赛截止时间</th>
						<th>比赛题目</th>
						<th>操作</th>
					</tr>
				</thead>
				<tbody>
				</tbody>
			</table>
			<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
			
		</div>

        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <script>
			
			// 加载当前比赛ID的函数，用于刷新显示当前比赛ID，假设后端接口为 /loadCurrentContestId，根据实际调整
			function loadCurrentContestId() {
				$.ajax({
					type: "GET",
					url: "/getCurrentContestId",
					dataType: "json",
					success: function (response) {
						console.log(response.id)
						const currentContestIdElement = document.getElementById('currentContestId');
						if (response && response.id) {
							currentContestIdElement.textContent = response.id;
						} else {
							currentContestIdElement.textContent = '暂无当前正在进行的比赛';
						}
					},
					error: function (xhr, status, error) {
						console.error('获取当前比赛ID出现错误：', xhr, status, error);
						const currentContestIdElement = document.getElementById('currentContestId');
						currentContestIdElement.textContent = '获取当前比赛ID出现错误，请稍后再试';
					}
				});
			}
		
			// 加载比赛列表函数
			function loadContestList() {
				$.ajax({
					type: "GET",
					url: "/get_contest_list",
					dataType: "json",
					success: function (response) {
						if (response.success) {
							var contestList = response.contestList;
							var contestTableBody = $("#contestTable tbody");
							contestTableBody.empty();
							for (var i = 0; i < contestList.length; i++) {
								var contest = contestList[i];
								var questionListHtml = "";
								// 遍历题目序列数组，生成题目列表的HTML
								if (contest.questions && contest.questions.length > 0) {
									for (var j = 0; j < contest.questions.length; j++) {
										// console.log(contest.questions[j])
										questionListHtml += "<li>" + contest.questions[j] + "</li>";
									}
									
								}
								var row = "<tr><td><input type='checkbox' class='contest-checkbox' data-contest-id='" + contest.id + "'></td><td>" + contest.id + "</td><td>" + contest.name + "</td><td>" + contest.deadline + "</td><td><ul>" + questionListHtml + "</ul></td><td><button class='btn btn-sm btn-danger delete-contest-btn' data-contest-id='" + contest.id + "'>删除</button> <button class='btn btn-sm btn-primary download-contest-btn' data-contest-id='" + contest.id + "'>下载</button> <button class='btn btn-sm btn-success activate-contest-btn' data-contest-id='" + contest.id + "'>激活比赛</button></td></tr>";
								contestTableBody.append(row);
							}
							// 为新添加的激活比赛按钮绑定点击事件
							$(".activate-contest-btn").click(function () {
								var contestId = $(this).data('contest-id');
								// 发起AJAX请求，向数据库的current_competition表写入当前比赛ID，这里假设后端接口为 /api/activateContest，根据实际调整
								$.ajax({
									type: "POST",
									url: "/api/activateContest",
									data: {
										contest_id: contestId
									},
									success: function (response) {
										// 写入成功后，重新加载当前比赛ID并刷新显示，调用加载当前比赛ID的函数（假设为loadCurrentContestId），根据实际调整
										alert(response.message)
										loadCurrentContestId();
									},
									error: function () {
										alert("激活比赛出现错误，请稍后再试");
									}
								});
							});
						} else {
							alert(response.message);
						}
					},
					error: function () {
						alert("获取比赛列表出现错误，请稍后再试");
					}
				});
			}

            // 批量删除比赛按钮点击事件处理
            $('#batchDeleteContestBtn').on('click', function () {
                var selectedContestIds = [];
                $('.contest-checkbox:checked').each(function () {
                    selectedContestIds.push($(this).data('contest-id'));
                });
                console.log("批量删除比赛，选中的比赛id列表:", selectedContestIds);
                if (selectedContestIds.length === 0) {
                    alert("请至少选择一个比赛进行批量删除操作");
                    return;
                }
                if (confirm("确定要批量删除所选比赛吗？此操作不可撤销！")) {
                    var formData = {
                        contest_ids: selectedContestIds
                    };
                    $.ajax({
                        type: "POST",
                        url: "/delete_contest",
                        data: formData,
                        dataType: "json",
                        success: function (response) {
                            if (response.success) {
                                alert(response.message);
                                loadContestList();
                            } else {
                                if (response.error_list && response.error_list.length > 0) {
                                    var errorMsg = "部分比赛删除失败，详细错误信息如下：\n";
                                    response.error_list.forEach(function (error, index) {
                                        errorMsg += `${index + 1}. ${error}\n`;
                                    });
                                    alert(errorMsg);
                                } else {
                                    alert(response.message);
                                }
                            }
                        },
                        error: function (xhr, status, error) {
                            console.log('批量删除比赛请求出现错误:', xhr, status, error);
                            alert("批量删除比赛出现错误，请稍后再试");
                        }
                    });
                }
            });

            $(document).on('click', '.delete-contest-btn', function () {
				var contestId = $(this).data('contest-id');
				console.log("准备删除比赛，比赛ID:", contestId);
				if (confirm("确定要删除该比赛吗？此操作不可撤销！")) {
					// 构造要发送的JSON数据格式
					var jsonData = {
						"contest_id": contestId
					};
					$.ajax({
						type: "POST",
						url: "/delete_contest",
						contentType: "application/json",
						headers: {
							// 明确设置Content-Type请求头，确保不会被其他因素干扰（有些情况下可能需要添加其他请求头，比如跨域相关的等）
							"Content-Type": "application/json"
						},
						data: JSON.stringify(jsonData),
						dataType: "json",
						success: function (response) {
							if (response.success) {
								alert(response.message);
								loadContestList();
							} else {
								alert(response.message);
							}
						},
						error: function (xhr, status, error) {
							console.log('删除比赛请求出现错误:', xhr, status, error);
							alert("删除比赛出现错误，请稍后再试");
						}
					});
				}
			});
			
			// 下载按钮点击事件处理
			$(document).on('click', '.download-contest-btn', function () {
				var contestId = $(this).data('contest-id');
				console.log("准备下载比赛相关文件，比赛ID:", contestId);
				if (confirm("确定要下载该比赛相关文件吗？")) {
					// 发起下载文件的 AJAX 请求，这里假设后端接口为 /download_contest_file
					var xhr = $.ajax({
						type: "GET",
						url: "/download_contest_file",
						data: {
							contest_id: contestId
						},
						xhrFields: {
							responseType: 'blob' // 设置响应类型为 blob，用于处理二进制文件数据
						},
						cache: false, // 设置为false，禁止缓存
						success: function (response) {
							var blob = new Blob([response], { type: 'application/zip' }); // 将返回的数据转为Blob对象，并指定类型为application/zip，对应zip文件类型
							var url = window.URL.createObjectURL(blob);
							var a = document.createElement('a');
							a.href = url;
							a.download = contestId + "_files.zip"; // 根据比赛ID生成文件名，你也可以根据后端返回的更准确信息来设置
							
							// 使用jqXHR对象获取响应头信息
							var competitionName = xhr.getResponseHeader('X-Competition-Name');
							console.log(competitionName);
							a.download = competitionName + "_files.zip"; 
							
							document.body.appendChild(a);
							a.click();
							document.body.removeChild(a);
							window.URL.revokeObjectURL(url);
						},
						error: function (xhr, status, error) {
							console.log('下载比赛文件请求出现错误:', xhr, status, error);
							if (xhr.status === 400) {
								alert("请求参数有误，请检查比赛ID是否正确");
							} else if (xhr.status === 404) {
								alert("未找到对应比赛文件或比赛信息，请确认");
							} else {
								alert("下载比赛文件出现错误，请稍后再试");
							}
						}
					});
				}
			});

            // 页面加载完成后加载比赛列表数据并展示
            $(document).ready(function () {
                loadContestList();
				loadCurrentContestId()
            });
        </script>
    </div>
  
  
  
  <script>
  
    $(document).ready(function () {
      // 点击导航栏链接切换对应功能区域显示，修正此处的点击事件绑定逻辑
      $('.nav-link').on('click', function (e) {
        e.preventDefault();
        var target = $(this).attr('href');
        $('.tab-pane').removeClass('show active');
        $(target).addClass('show active');
      });

      // 页面加载时获取用户列表并填充到表格中（用于用户管理功能区域）
      function loadUserList() {
        $.ajax({
          type: "GET",
          url: "/get_user_list",
          dataType: "json",
          success: function (response) {
            if (response.success) {
              var userList = response.userList;
              var userTableBody = $("#userList");
              userTableBody.empty();
              // 遍历用户数据并添加到表格行中
              for (var i = 0; i < userList.length; i++) {
                var user = userList[i];
                var row = "<tr><td><input type='checkbox' class='user-checkbox' data-user-id='" + user.id + "'></td><td>" + user.id + "</td><td>" + user.username + "</td><td>" + (user.is_admin? "是" : "否") + "</td><td><button class='btn btn-sm btn-primary reset-password-btn' data-user-id='" + user.id + "'>重置密码</button> <button class='btn btn-sm btn-danger delete-user-btn' data-user-id='" + user.id + "'>删除</button></td></tr>";
                userTableBody.append(row);
              }
            } else {
              alert(response.message);
            }
          },
          error: function () {
            alert("获取用户列表出现错误，请稍后再试");
          }
        });
      }

      loadUserList();

      // 为创建用户表单添加提交事件处理，防止页面刷新并以弹窗提示结果
      $('#createUserForm').on('submit', function (e) {
        e.preventDefault();
        var formData = $(this).serialize();
        $.ajax({
          type: "POST",
          url: $(this).attr('action'),
          data: formData,
          dataType: "json",
          success: function (response) {
            alert(response.message);
            // 新增代码，在创建用户成功后重新加载用户列表，保持在当前页面
            if (response.success) {
              loadUserList();
            }
          },
          error: function () {
            alert("创建用户出现错误，请稍后再试");
          }
        });
      });

      // 为批量创建用户表单添加提交事件处理
      $('#batchCreateUserForm').on('submit', function (e) {
        e.preventDefault();
        var formData = $(this).serialize();
        $.ajax({
          type: "POST",
          url: $(this).attr('action'),
          data: formData,
          dataType: "json",
          success: function (response) {
            alert(response.message);
            // 新增代码，在批量创建用户成功后重新加载用户列表，保持在当前页面
            if (response.success) {
              loadUserList();
            }
          },
          error: function () {
            alert("批量创建用户出现错误，请稍后再试");
          }
        });
      });

      // 全选复选框点击事件处理
      $('#selectAllCheckbox').on('click', function () {
        $('.user-checkbox').prop('checked', $(this).prop('checked'));
      });

      // 批量重置密码按钮点击事件处理
      $('#batchResetPasswordBtn').on('click', function () {
        var selectedUserIds = [];
        $('.user-checkbox:checked').each(function () {
          selectedUserIds.push($(this).data('user-id'));
        });
        console.log("批量重置密码，选中的用户id列表:", selectedUserIds);
        if (selectedUserIds.length === 0) {
          alert("请至少选择一个用户进行批量重置密码操作");
          return;
        }
		console.log(selectedUserIds)
        if (confirm("确定要将所选用户的密码批量重置为 12345 吗？此操作不可撤销！")) {
          $.ajax({
            type: "POST",
            url: "/batch_reset_password",
            data: {
              user_ids: selectedUserIds
            },
            dataType: "json",
            success: function (response) {
              if (response.success) {
                alert(response.message);
                loadUserList();
              } else {
                alert(response.message);
              }
            },
            error: function () {
              alert("批量重置密码出现错误，请稍后再试");
            }
          });
        }
      });

	// 批量删除按钮点击事件处理
	$('#batchDeleteBtn').on('click', function () {
		var selectedUserIds = [];
		$('.user-checkbox:checked').each(function () {
			selectedUserIds.push($(this).data('user-id'));
		});
		console.log("批量删除，选中的用户id列表:", selectedUserIds);
		if (selectedUserIds.length === 0) {
			alert("请至少选择一个用户进行批量删除操作");
			return;
		}
		if (confirm("确定要批量删除所选用户吗？此操作不可撤销！")) {
			var data = {
				user_ids: selectedUserIds
			};
			$.ajax({
				type: "POST",
				url: "/batch_delete_users",
				contentType: "application/json",
				data: JSON.stringify(data),
				dataType: "json",
				success: function (response) {
					console.log("批量删除请求成功响应，响应数据:", response);
					if (response.success === true) {
						
						alert(response.message);
						loadUserList(); // 在单个用户删除成功后重新加载用户列表，保持在当前页面
					} else {
						if (response.error_list && response.error_list.length > 0) {
							var errorMsg = "部分用户删除失败，详细错误信息如下：\n";
							response.error_list.forEach(function (error, index) {
								errorMsg += `${index + 1}. ${error}\n`;
							});
							alert(errorMsg);
						} else {
							alert(response.message);
						}
					}
				},
				error: function (xhr, status, error) {
					console.log('批量删除请求出现错误:', xhr, status, error);
					alert("批量删除用户出现错误，请稍后再试");
				}
			});
		}
	});

      // 为单个删除用户按钮添加点击事件处理，修改此处逻辑，在删除成功后重新加载用户列表
      $(document).on('click', '.delete-user-btn', function () {
        var userId = $(this).data('user-id');
        if (confirm("确定要删除用户ID为 " + userId + " 的用户吗？此操作不可撤销！")) {
          $.ajax({
            type: "POST",
            url: "/delete_user",
            data: {
              user_id: userId
            },
            dataType: "json",
            success: function (response) {
				
              if (response.success) {
                alert(response.message);
                loadUserList(); // 在单个用户删除成功后重新加载用户列表，保持在当前页面
              } else {
                alert(response.message);
              }
            },
            error: function () {
              alert("删除用户出现错误，请稍后再试");
            }
          });
        }
      });

      // 为重置密码按钮添加点击事件处理，打开模态框
      $(document).on('click', '.reset-password-btn', function () {
        var userId = $(this).data('user-id');
        $('#resetUserId').val(userId);
        $('#resetPasswordModal').modal('show');
      });

      // 为确认重置密码按钮添加点击事件处理，发送请求重置密码
      $('#confirmResetPassword').on('click', function () {
        var userId = $('#resetUserId').val();
        $.ajax({
          type: "POST",
          url: "/reset_password",
          data: {
            user_id: userId
          },
          dataType: "json",
          success: function (response) {
            if (response.success) {
              alert(response.message);
              $('#resetPasswordModal').modal('hide');
              loadUserList();
            } else {
              alert(response.message);
            }
          },
          error: function () {
            alert("重置密码出现错误，请稍后再试");
          }
        });
      });
    });
  </script>
</body>

</html>